package com.qf.mq;

import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardReport;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.channels.Channel;

/**
 * author:z
 * time:2022/1/3 21:55
 * description:从mq中监听同步到es中
 */
@Slf4j
@Component
public class ReportMqListener {

    @Resource
    RestHighLevelClient restHighLevelClient;

    //从mq中监听到同步到es中
    @RabbitListener(queues = RabbitMQConstants.TOPIC_UPDATE_SMS_REPORT)
    public boolean syncLog(StandardReport report, Channel channel, Message message){
        //修改es文档
        UpdateRequest request = new UpdateRequest();
        //文档索引名称
        request.index(RabbitMQConstants.TOPIC_UPDATE_SMS_REPORT);
        //添加文档内容
        request.doc(report);
        try {
            //es连接客户端 更新
            UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
            //结果是否创建
            if (update.getResult().equals("UPDATE")){
                return true;
            }
        } catch (IOException e) {
            log.error("log 同步 ES 出错");
            e.printStackTrace();
        }
        return false;
    }

}
